using System;
using System.Security.Cryptography;
using System.Windows.Forms;

namespace Krile.Subsystem
{
    /// <summary>
    /// Security startup helper
    /// </summary>
    internal static class Security
    {
        private static Krile.Imported.Snippets.Security.AESEncryptor AESEncryptor = new Krile.Imported.Snippets.Security.AESEncryptor();

        internal static string EncryptString(string source)
        {
            return AESEncryptor.AESEncrypt(source);
        }

        internal static string DecryptString(string crypt)
        {
            return AESEncryptor.AESDecrypt(crypt);
        }

        internal static bool SecureStart()
        {
            for (int count = 0; count < 3; count++)
            {
                if (count != 0)
                    MessageBox.Show(Lang.Msg.SecureStart_InvalidPassword,
                        "Secure Startup Error", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                using (Forms.Dialogs.Editor.SecureStart ss = new Krile.Forms.Dialogs.Editor.SecureStart())
                {
                    if (ss.ShowDialog() == System.Windows.Forms.DialogResult.Cancel)
                        return false;
                    if (CheckPassword(ss.PasswordText))
                    {
                        SetPassword(ss.PasswordText);
                        return true;
                    }
                }
            }
            MessageBox.Show(Lang.Msg.SecureStart_TooMuchMistake,
                "Secure Startup Error", MessageBoxButtons.OK, MessageBoxIcon.Hand);
            return false;
        }

        internal static void DefaultStart()
        {
            if (Core.Config.Security.cryptokey == null)
            {
                using (HMACMD5 md5 = new HMACMD5())
                {
                    Core.Config.Security.cryptokey = BitConverter.ToString(
                        md5.ComputeHash(System.Text.Encoding.ASCII.GetBytes(
                        Environment.MachineName + "/" + Environment.UserName + "/" + Guid.NewGuid().ToString())));
                }
            }
            SetPassword(Core.Config.Security.cryptokey + Define.CryptoKey);
        }

        private static bool CheckPassword(string password)
        {
            byte[] checkBite = System.Text.Encoding.ASCII.GetBytes(password);
            using (SHA512Managed sha = new SHA512Managed())
            {
                if (BitConverter.ToString(sha.ComputeHash(checkBite)) == Core.Config.Security.KeyHash)
                    return true;
                else
                    return false;
            }
        }

        private static void SetPassword(string text)
        {
            AESEncryptor.password = text;
        }
    }
}
